package com.software.loginregister.fragment.homecategoryfragment;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.github.chrisbanes.photoview.PhotoView;
import com.software.loginregister.R;
import com.software.loginregister.adapter.FridgeExpandableAdapter;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.vo.ImageFoodGroupVO;
import com.software.loginregister.entity.vo.RefrigeratorFoodVO;
import com.software.loginregister.util.CameraUtils;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import lombok.NonNull;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import android.graphics.drawable.Drawable;

public class FridgeFragment extends Fragment {
    private static final String TAG = "FridgeFragment";
    private ExpandableListView expandableListView;
    private FridgeExpandableAdapter expandableAdapter;

    private CameraUtils cameraUtils;
    private ImageButton cameraButton;
    private SwipeRefreshLayout swipeRefreshLayout;
    private Long userId;
    private static final String[] REQUIRED_PERMISSIONS;
    static {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) { // Android 13+
            REQUIRED_PERMISSIONS = new String[] {
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_MEDIA_IMAGES
            };
        } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { // Android 10+
            REQUIRED_PERMISSIONS = new String[] {
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE
            };
        } else {
            REQUIRED_PERMISSIONS = new String[] {
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fridge, container, false);
        initViews(view);
        // 加载冰箱列表
        loadFoodList();

        return view;
    }

    private void initViews(View view) {
        // 初始化下拉刷新
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setOnRefreshListener(this::loadFoodList);
        swipeRefreshLayout.setColorSchemeResources(R.color.primary);

        ProgressDialog progressDialog = new ProgressDialog(requireContext());
        progressDialog.setMessage("正在上传图片...");
        progressDialog.setCancelable(false);
        // 初始化相机工具类
        cameraUtils = new CameraUtils(this);


        // 初始化相机按钮
        cameraButton = view.findViewById(R.id.iv_fridge_camera);
        cameraButton.setOnClickListener(v -> {
            Log.d(TAG, "Camera button clicked");
            requestAndHandlePermissions();
        });

        // 初始化冰箱列表
        expandableListView = view.findViewById(R.id.rv_fridge_items);
        expandableAdapter = new FridgeExpandableAdapter(requireContext());
        expandableListView.setAdapter(expandableAdapter);

        // 设置组项点击事件
        expandableListView.setOnGroupClickListener((parent, v, groupPosition, id) -> {
            if (expandableListView.isGroupExpanded(groupPosition)) {
                expandableListView.collapseGroup(groupPosition);
            } else {
                // 展开当前组，收起其他组
                for (int i = 0; i < expandableAdapter.getGroupCount(); i++) {
                    if (i != groupPosition) {
                        expandableListView.collapseGroup(i);
                    }
                }
                expandableListView.expandGroup(groupPosition);
            }
            return true;
        });

        // 添加长按删除功能
        expandableListView.setOnItemLongClickListener((parent, v, position, id) -> {
            // 判断是否为组项
            long packedPosition = expandableListView.getExpandableListPosition(position);
            int itemType = ExpandableListView.getPackedPositionType(packedPosition);
            if (itemType == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
                int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
                String captureTime = expandableAdapter.getGroupTime(groupPosition);
                List<RefrigeratorFoodVO> groupFoods = expandableAdapter.getGroupFoods(groupPosition);
                Object groupObject = expandableAdapter.getGroup(groupPosition);
                if (!(groupObject instanceof ImageFoodGroupVO)) {
                    Toast.makeText(requireContext(), "数据类型错误", Toast.LENGTH_SHORT).show();
                    return true;
                }
                ImageFoodGroupVO group = (ImageFoodGroupVO) groupObject;

                // 显示确认对话框
                new AlertDialog.Builder(requireContext())
                        .setTitle("确认删除")
                        .setMessage("确定要删除这个时间段的所有食物吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            // 删除该组所有食物
                            for (RefrigeratorFoodVO food : groupFoods) {
                                deleteFoodItem(food.getId());
                            }
                            // 删除父项图片
                            deleteImageRecord(group.getImageId());
                        })
                        .setNegativeButton("取消", null)
                        .show();
                return true;
            }
            return false;
        });


        // 设置详情点击监听器
        expandableAdapter.setOnDetailClickListener(food -> {
            Log.d(TAG, "onDetail: " + food.getFoodName());
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            View dialogView = getLayoutInflater().inflate(R.layout.dialog_food_detial, null);

            // 初始化视图
            ImageView ivFoodImage = dialogView.findViewById(R.id.iv_food_image);
            TextView tvFoodName = dialogView.findViewById(R.id.tv_food_name);
            TextView tvStorageTime = dialogView.findViewById(R.id.tv_storage_time);
            TextView tvStoredHours = dialogView.findViewById(R.id.tv_stored_hours);
            TextView tvOfficial = dialogView.findViewById(R.id.tv_official);
            TextView tvStatus = dialogView.findViewById(R.id.tv_status);
//            调用添加图片的弹框
            ivFoodImage.setOnClickListener(v -> {
                if (!TextUtils.isEmpty(food.getFoodImageUrl())) {
                    // 创建全屏对话框
                    AlertDialog.Builder builder2 = new AlertDialog.Builder(requireContext(), android.R.style.Theme_Black_NoTitleBar_Fullscreen);
                    View previewView = getLayoutInflater().inflate(R.layout.dialog_image_preview, null);
                    PhotoView photoView = previewView.findViewById(R.id.photo_view);
                    previewView.setBackgroundColor(getResources().getColor(android.R.color.white));
                    // 加载图片
                    Glide.with(requireContext())
                            .load(food.getFoodImageUrl())
                            .error(R.drawable.ic_food_icon)  // 添加错误占位图
                            .transition(DrawableTransitionOptions.withCrossFade())
                            .into(photoView);

                    AlertDialog dialog = builder2.setView(previewView).create();

                    // 添加关闭按钮（可选）
                    ImageView closeButton = previewView.findViewById(R.id.iv_close);
                    if (closeButton != null) {
                        closeButton.setOnClickListener(clickedView -> dialog.dismiss());
                    }

                    // 显示对话框
                    dialog.show();
                } else {
                    // 如果没有图片，则显示选择图片的对话框
                    cameraUtils.showImagePickerDialog(ivFoodImage, imageFile -> {
                        progressDialog.show(); // 显示加载对话框

                        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), imageFile);
                        MultipartBody.Part imagePart = MultipartBody.Part.createFormData("file", imageFile.getName(), requestBody);

                        // 调用上传 API
                        RetrofitClient.getInstance()
                                .getRefrigeratorApi()
                                .uploadFoodImage(food.getId(), imagePart)
                                .enqueue(new Callback<Result<String>>() {
                                    @Override
                                    public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                                        progressDialog.dismiss(); // 隐藏加载对话框
                                        if (response.isSuccessful() && response.body() != null) {
                                            Result<String> result = response.body();
                                            if (result.getCode() == 1) {
                                                Toast.makeText(requireContext(), "图片上传成功", Toast.LENGTH_SHORT).show();
                                                // 刷新食物列表
                                                loadFoodList();
                                            } else {
                                                Toast.makeText(requireContext(), "上传失败：" + result.getMsg(), Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    }

                                    @Override
                                    public void onFailure(Call<Result<String>> call, Throwable t) {
                                        progressDialog.dismiss();
                                        Toast.makeText(requireContext(), "上传失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                                    }
                                });
                    });

                }
            });

            ivFoodImage.setOnLongClickListener(v -> {
                // 显示选择图片的对话框
                cameraUtils.showImagePickerDialog(ivFoodImage, imageFile -> {
                    progressDialog.show(); // 显示加载对话框

                    RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), imageFile);
                    MultipartBody.Part imagePart = MultipartBody.Part.createFormData("file", imageFile.getName(), requestBody);

                    // 调用上传 API
                    RetrofitClient.getInstance()
                            .getRefrigeratorApi()
                            .uploadFoodImage(food.getId(), imagePart)
                            .enqueue(new Callback<Result<String>>() {
                                @Override
                                public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                                    progressDialog.dismiss(); // 隐藏加载对话框
                                    if (response.isSuccessful() && response.body() != null) {
                                        Result<String> result = response.body();
                                        if (result.getCode() == 1) {
                                            Toast.makeText(requireContext(), "图片更新成功", Toast.LENGTH_SHORT).show();
                                            // 刷新食物列表
                                            loadFoodList();
                                        } else {
                                            Toast.makeText(requireContext(), "更新失败：" + result.getMsg(), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }

                                @Override
                                public void onFailure(Call<Result<String>> call, Throwable t) {
                                    progressDialog.dismiss();
                                    Toast.makeText(requireContext(), "更新失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                });
                return true; // 返回 true 表示已处理长按事件
            });
            // 设置食物图片
            if (!TextUtils.isEmpty(food.getFoodImageUrl())) {
                Glide.with(requireContext())
                        .load(food.getFoodImageUrl())
                        .placeholder(R.drawable.ic_food_icon)
                        .error(R.drawable.ic_food_icon)
                        .into(ivFoodImage);
            }


            // 设置食物名称
            tvFoodName.setText(food.getFoodName());

            // 格式化并设置存放时间
            try {
                SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date date = inputFormat.parse(food.getStorageTime());
                tvStorageTime.setText(outputFormat.format(date));
            } catch (Exception e) {
                tvStorageTime.setText(food.getStorageTime());
            }

            // 设置已存放时间
            tvStoredHours.setText(food.getStoredTimeText());

            // 设置保存建议
            tvOfficial.setText(food.getOfficial());

            // 设置状态
            if (food.getStatus() == 1) {
                tvStatus.setText("状态：新鲜");
                tvStatus.setTextColor(getResources().getColor(R.color.green_primary));
            } else {
                tvStatus.setText("状态：已过期");
                tvStatus.setTextColor(getResources().getColor(R.color.error_text));
            }

            builder.setView(dialogView)
                    .show();
        });

        // 设置删除点击监听器
        expandableAdapter.setOnDeleteClickListener(foodId -> {
            new AlertDialog.Builder(requireContext())
                    .setTitle("确认删除")
                    .setMessage("确定要删除这个食物吗？")
                    .setPositiveButton("确定", (dialog, which) -> {
                        deleteFoodItem(foodId);
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });

    }


    // 添加新的权限请求处理方法
    private void requestAndHandlePermissions() {
        if (hasAllPermissions()) {
            Log.d(TAG, "All permissions already granted");
            cameraUtils.showCameraDialog();
        } else {
            Log.d(TAG, "Requesting permissions");
            requestPermissions(REQUIRED_PERMISSIONS, CameraUtils.REQUEST_CAMERA_PERMISSION);
        }
    }

    // 修改权限检查方法
    private boolean hasAllPermissions() {
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(requireContext(), permission)
                    != PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "Missing permission: " + permission);
                return false;
            }
        }
        Log.d(TAG, "All permissions granted");
        return true;
    }

    // 添加权限请求方法
    private void requestCameraPermissions() {
        Log.d(TAG, "Requesting camera permissions");
        requestPermissions(REQUIRED_PERMISSIONS, CameraUtils.REQUEST_CAMERA_PERMISSION);
    }
    private boolean checkAndRequestPermissions() {
        boolean allPermissionsGranted = true;
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(requireContext(), permission)
                    != PackageManager.PERMISSION_GRANTED) {
                allPermissionsGranted = false;
                break;
            }
        }

        if (!allPermissionsGranted) {
            requestPermissions(REQUIRED_PERMISSIONS, CameraUtils.REQUEST_CAMERA_PERMISSION);
            return false;
        }
        return true;
    }

    // 添加删除图片记录的方法
    private void deleteImageRecord(Long imageId) {
        RetrofitClient.getInstance()
                .getRefrigeratorApi()
                .deleteImage(imageId)
                .enqueue(new Callback<Result<String>>() {
                    @Override
                    public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                        if (response.isSuccessful()) {
                            Result<String> result = response.body();
                            if (result != null) {
                                Toast.makeText(requireContext(), result.getMsg(), Toast.LENGTH_SHORT).show();
                                if (result.getCode() == 1) {
                                    loadFoodList(); // 删除成功后重新加载列表
                                }
                            } else {
                                Toast.makeText(requireContext(), "删除失败：响应为空", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(requireContext(), "删除失败：" + response.code(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<String>> call, Throwable t) {
                        Toast.makeText(requireContext(), "删除失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.e("FridgeFragment", "删除图片记录失败", t);
                    }
                });
    }

    // 拍照请求权限
// 修改权限结果处理方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CameraUtils.REQUEST_CAMERA_PERMISSION) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }

            if (allGranted) {
                Log.d(TAG, "All permissions granted in result");
                cameraUtils.showCameraDialog();
            } else {
                Log.d(TAG, "Some permissions denied");
                // 检查是否有任何权限需要显示解释
                boolean shouldShowRationale = false;
                for (String permission : permissions) {
                    if (shouldShowRequestPermissionRationale(permission)) {
                        shouldShowRationale = true;
                        break;
                    }
                }

                if (shouldShowRationale) {
                    showPermissionExplanationDialog();
                } else {
                    showSettingsDialog();
                }
            }
        }
    }

    // 修改权限说明对话框
    private void showPermissionExplanationDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("需要权限")
                .setMessage("此功能需要相机和存储权限才能正常工作。请允许所有请求的权限。")
                .setPositiveButton("重试", (dialog, which) -> {
                    Log.d(TAG, "Retrying permission request");
                    requestAndHandlePermissions();
                })
                .setNegativeButton("取消", null)
                .create()
                .show();
    }

    // 修改设置对话框
    private void showSettingsDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("权限设置")
                .setMessage("请在设置中手动开启相机和存储权限，否则无法使用拍照功能。")
                .setPositiveButton("去设置", (dialog, which) -> {
                    Log.d(TAG, "Opening settings");
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", requireContext().getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                })
                .setNegativeButton("取消", null)
                .create()
                .show();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        cameraUtils.onActivityResult(requestCode, resultCode, data);
    }

    // 加载冰箱列表
    private void loadFoodList() {
        Log.d(TAG, "loadFridgeData: Starting to load data");
        userId = SharedPreferencesUtil.getUserId(requireContext());
        Log.d(TAG, "loadFridgeData: User ID: " + userId);

        RetrofitClient.getInstance()
                .getRefrigeratorApi()
                .getFoodList(userId)
                .enqueue(new Callback<Result<List<ImageFoodGroupVO>>>() {
                    @Override
                    public void onResponse(Call<Result<List<ImageFoodGroupVO>>> call,
                                           Response<Result<List<ImageFoodGroupVO>>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            Result<List<ImageFoodGroupVO>> result = response.body();
                            if (result.getCode() == 1 && result.getData() != null) {
                                Log.d(TAG, "loadFridgeData: Received " + result.getData().size() + " groups");
                                // 更新适配器数据
                                expandableAdapter.updateDataWithGroups(result.getData());
                            }
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onFailure(Call<Result<List<ImageFoodGroupVO>>> call, Throwable t) {
                        Toast.makeText(requireContext(), "获取食物列表失败", Toast.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }


    // 处理删除食物
    public void deleteFoodItem(Long foodId) {

        RetrofitClient.getInstance()
                .getRefrigeratorApi()
                .deleteFood(foodId, userId)
                .enqueue(new Callback<Result<String>>() {
                    @Override
                    public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            Result<String> result = response.body();
                            if (result.getCode() == 1) {
                                Toast.makeText(requireContext(), "删除成功", Toast.LENGTH_SHORT).show();
                                loadFoodList(); // 重新加载列表
                            } else {
                                Toast.makeText(requireContext(), result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<String>> call, Throwable t) {
                        Toast.makeText(requireContext(), "删除失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }
}